<template>
  <div class="class-list">
    <div class="page-title">班级管理</div>
    
    <!-- 搜索表单 -->
    <a-card class="search-form mb-16">
      <a-form
        ref="searchFormRef"
        :model="searchForm"
        layout="inline"
        @finish="handleSearch"
      >
        <a-form-item label="班级名称" name="className">
          <a-input
            v-model:value="searchForm.className"
            placeholder="请输入班级名称"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="年级" name="gradeLevel">
          <a-select
            v-model:value="searchForm.gradeLevel"
            placeholder="请选择年级"
            allow-clear
            style="width: 120px"
          >
            <a-select-option :value="1">一年级</a-select-option>
            <a-select-option :value="2">二年级</a-select-option>
            <a-select-option :value="3">三年级</a-select-option>
            <a-select-option :value="4">四年级</a-select-option>
            <a-select-option :value="5">五年级</a-select-option>
            <a-select-option :value="6">六年级</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="学年" name="academicYear">
          <a-select
            v-model:value="searchForm.academicYear"
            placeholder="请选择学年"
            allow-clear
            style="width: 150px"
          >
            <a-select-option value="2023-2024">2023-2024</a-select-option>
            <a-select-option value="2024-2025">2024-2025</a-select-option>
            <a-select-option value="2025-2026">2025-2026</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="班主任" name="headTeacher">
          <a-input
            v-model:value="searchForm.headTeacher"
            placeholder="请输入班主任姓名"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="loading">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
    
    <!-- 操作按钮 -->
    <div class="action-buttons mb-16">
      <a-space>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          添加班级
        </a-button>
        
        <a-button
          type="primary"
          ghost
          :disabled="!selectedRowKeys.length"
          @click="handleBatchDelete"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
        
        <a-button @click="handleIntelligentAssignment">
          <template #icon>
            <ThunderboltOutlined />
          </template>
          智能分班
        </a-button>
        
        <a-button @click="handleExport">
          <template #icon>
            <ExportOutlined />
          </template>
          导出班级
        </a-button>
      </a-space>
    </div>
    
    <!-- 班级列表表格 -->
    <a-card class="data-table">
      <a-table
        :columns="columns"
        :data-source="classList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :scroll="{ x: 1000 }"
        @change="handleTableChange"
      >
        <!-- 班级名称列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'className'">
            <a @click="handleViewStudents(record)" class="class-name-link">
              {{ record.className }}
            </a>
          </template>
          
          <!-- 年级列 -->
          <template v-else-if="column.key === 'gradeLevel'">
            <a-tag color="blue">{{ getGradeName(record.gradeLevel) }}</a-tag>
          </template>
          
          <!-- 人数统计列 -->
          <template v-else-if="column.key === 'studentCount'">
            <a-progress
              :percent="(record.currentCount / record.maxCapacity) * 100"
              :format="() => `${record.currentCount}/${record.maxCapacity}`"
              :stroke-color="getProgressColor(record.currentCount, record.maxCapacity)"
              size="small"
            />
          </template>
          
          <!-- 班主任列 -->
          <template v-else-if="column.key === 'headTeacher'">
            <a-space>
              <a-avatar :size="24">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <span>{{ record.headTeacherName }}</span>
            </a-space>
          </template>
          
          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewStudents(record)">
                学生列表
              </a-button>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个班级吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 智能分班弹窗 -->
    <a-modal
      v-model:open="intelligentAssignmentVisible"
      title="智能分班"
      width="600px"
      @ok="handleIntelligentAssignmentSubmit"
      @cancel="intelligentAssignmentVisible = false"
    >
      <a-form
        ref="assignmentFormRef"
        :model="assignmentForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="年级" name="gradeLevel">
          <a-select
            v-model:value="assignmentForm.gradeLevel"
            placeholder="请选择年级"
          >
            <a-select-option :value="1">一年级</a-select-option>
            <a-select-option :value="2">二年级</a-select-option>
            <a-select-option :value="3">三年级</a-select-option>
            <a-select-option :value="4">四年级</a-select-option>
            <a-select-option :value="5">五年级</a-select-option>
            <a-select-option :value="6">六年级</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="班级数量" name="classCount">
          <a-input-number
            v-model:value="assignmentForm.classCount"
            :min="1"
            :max="10"
            placeholder="请输入班级数量"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="每班人数" name="studentsPerClass">
          <a-input-number
            v-model:value="assignmentForm.studentsPerClass"
            :min="20"
            :max="50"
            placeholder="请输入每班人数"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="分班策略">
          <a-checkbox-group v-model:value="assignmentForm.strategies">
            <a-checkbox value="academic">成绩均衡</a-checkbox>
            <a-checkbox value="gender">性别平衡</a-checkbox>
            <a-checkbox value="talent">特长分布</a-checkbox>
            <a-checkbox value="social">社交因素</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DeleteOutlined,
  ThunderboltOutlined,
  ExportOutlined,
  UserOutlined
} from '@ant-design/icons-vue'

const router = useRouter()

// 表单引用
const searchFormRef = ref()
const assignmentFormRef = ref()

// 加载状态
const loading = ref(false)

// 智能分班弹窗显示状态
const intelligentAssignmentVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  className: '',
  gradeLevel: undefined,
  academicYear: undefined,
  headTeacher: ''
})

// 智能分班表单
const assignmentForm = reactive({
  gradeLevel: undefined,
  classCount: 4,
  studentsPerClass: 35,
  strategies: ['academic', 'gender']
})

// 选中的行
const selectedRowKeys = ref([])

// 班级列表
const classList = ref([
  {
    id: '1',
    classId: 'C2024001',
    className: '一年级1班',
    gradeLevel: 1,
    academicYear: '2024-2025',
    headTeacherId: 'T2024001',
    headTeacherName: '王老师',
    maxCapacity: 40,
    currentCount: 38,
    classroom: '101教室'
  },
  {
    id: '2',
    classId: 'C2024002',
    className: '一年级2班',
    gradeLevel: 1,
    academicYear: '2024-2025',
    headTeacherId: 'T2024002',
    headTeacherName: '李老师',
    maxCapacity: 40,
    currentCount: 35,
    classroom: '102教室'
  },
  {
    id: '3',
    classId: 'C2024003',
    className: '二年级1班',
    gradeLevel: 2,
    academicYear: '2024-2025',
    headTeacherId: 'T2024003',
    headTeacherName: '张老师',
    maxCapacity: 40,
    currentCount: 42,
    classroom: '201教室'
  },
  {
    id: '4',
    classId: 'C2024004',
    className: '三年级1班',
    gradeLevel: 3,
    academicYear: '2024-2025',
    headTeacherId: 'T2024004',
    headTeacherName: '刘老师',
    maxCapacity: 40,
    currentCount: 36,
    classroom: '301教室'
  }
])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 4,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: '班级编号',
    dataIndex: 'classId',
    key: 'classId',
    width: 120
  },
  {
    title: '班级名称',
    key: 'className',
    width: 150
  },
  {
    title: '年级',
    key: 'gradeLevel',
    width: 100,
    align: 'center'
  },
  {
    title: '学年',
    dataIndex: 'academicYear',
    key: 'academicYear',
    width: 120
  },
  {
    title: '班主任',
    key: 'headTeacher',
    width: 150
  },
  {
    title: '人数统计',
    key: 'studentCount',
    width: 150,
    align: 'center'
  },
  {
    title: '教室',
    dataIndex: 'classroom',
    key: 'classroom',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}))

// 获取年级名称
const getGradeName = (level) => {
  const gradeNames = {
    1: '一年级',
    2: '二年级',
    3: '三年级',
    4: '四年级',
    5: '五年级',
    6: '六年级'
  }
  return gradeNames[level] || '未知年级'
}

// 获取进度条颜色
const getProgressColor = (current, max) => {
  const ratio = current / max
  if (ratio >= 1) return '#ff4d4f'
  if (ratio >= 0.9) return '#faad14'
  return '#52c41a'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadClassList()
}

// 重置搜索
const handleReset = () => {
  searchFormRef.value.resetFields()
  pagination.current = 1
  loadClassList()
}

// 添加班级
const handleAdd = () => {
  message.info('添加班级功能开发中...')
}

// 查看学生列表
const handleViewStudents = (record) => {
  router.push(`/students?classId=${record.id}`)
}

// 编辑班级
const handleEdit = (record) => {
  message.info('编辑班级功能开发中...')
}

// 删除班级
const handleDelete = async (record) => {
  try {
    // 调用删除API
    // await classApi.deleteClass(record.id)
    
    message.success('删除成功')
    loadClassList()
  } catch (error) {
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个班级吗？`,
    onOk: async () => {
      try {
        // 调用批量删除API
        // await classApi.batchDeleteClasses(selectedRowKeys.value)
        
        message.success('批量删除成功')
        selectedRowKeys.value = []
        loadClassList()
      } catch (error) {
        message.error('批量删除失败')
      }
    }
  })
}

// 智能分班
const handleIntelligentAssignment = () => {
  intelligentAssignmentVisible.value = true
}

// 提交智能分班
const handleIntelligentAssignmentSubmit = async () => {
  try {
    // 调用智能分班API
    // await classApi.intelligentAssignment(assignmentForm)
    
    message.success('智能分班完成')
    intelligentAssignmentVisible.value = false
    loadClassList()
  } catch (error) {
    message.error('智能分班失败')
  }
}

// 导出班级
const handleExport = () => {
  message.info('导出功能开发中...')
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadClassList()
}

// 加载班级列表
const loadClassList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      ...searchForm,
      page: pagination.current,
      pageSize: pagination.pageSize
    }
    
    // 调用API获取数据
    // const response = await classApi.getClassList(params)
    // classList.value = response.data
    // pagination.total = response.total
    
    console.log('加载班级列表', params)
  } catch (error) {
    message.error('加载班级列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadClassList()
})
</script>

<style scoped>
.class-list {
  padding: 0;
}

.search-form {
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.data-table {
  border-radius: 8px;
}

.class-name-link {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
}

.class-name-link:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .ant-btn {
    width: 100%;
  }
}
</style>